const jwt = require('jsonwebtoken');

const generateToken = (user) => {
  const payload = {
    id: user.id,
    username: user.username,
    email: user.email
  };

  const expiresInSeconds = parseInt(process.env.JWT_EXPIRES_IN, 10) || 7200; // 默认7200秒 (2小时)

  return jwt.sign(payload, process.env.JWT_SECRET, {
    expiresIn: expiresInSeconds
  });
};

const verifyToken = (token) => {
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    return {
      valid: true,
      expired: false,
      payload: decoded
    };
  } catch (error) {
    return {
      valid: false,
      expired: error.name === 'TokenExpiredError',
      payload: null
    };
  }
};

module.exports = {
  generateToken,
  verifyToken
}; 